package com.baijiayun.liveuibase.devicetesting.fragment

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.baijiayun.livecore.utils.LPReportUtil
import com.baijiayun.liveuibase.R
import com.baijiayun.liveuibase.devicetesting.DeviceTestingViewModel
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.bjy_base_fragment_device_testing_result.*
import java.text.DateFormat
import java.util.*

class DeviceTestingResultFragment : Fragment() {
    private lateinit var viewModel: DeviceTestingViewModel
    private val netQualityText = arrayOf(
            R.string.bjy_base_device_testing_result_net_terrible,
            R.string.bjy_base_device_testing_result_net_bad,
            R.string.bjy_base_device_testing_result_net_normal,
            R.string.bjy_base_device_testing_result_net_good,
            R.string.bjy_base_device_testing_result_net_very_good
    )
    private val netQualityColor = arrayOf(
            R.color.bjy_base_device_testing_net_terrible,
            R.color.bjy_base_device_testing_net_bad,
            R.color.bjy_base_device_testing_net_normal,
            R.color.bjy_base_device_testing_net_good,
            R.color.bjy_base_device_testing_net_good
    )

    private val mmkv by lazy {
        MMKV.mmkvWithID("device_testing")
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.bjy_base_fragment_device_testing_result, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = ViewModelProvider(requireActivity()).get(DeviceTestingViewModel::class.java)
        initView()
    }

    private fun initView() {
        bjy_base_fragment_device_testing_result_net_iv.isEnabled = true
        bjy_base_fragment_device_testing_result_camera_iv.isEnabled = true
        bjy_base_fragment_device_testing_result_speaker_iv.isEnabled = true
        bjy_base_fragment_device_testing_result_mic_iv.isEnabled = true
        bjy_base_fragment_device_testing_result_oc_tv.text = "Android ${Build.VERSION.RELEASE}"
        bjy_base_fragment_device_testing_result_client_tv.text = "V ${LPReportUtil.getVersionName(context)}"
        bjy_base_fragment_device_testing_result_net_ip_tv.text = viewModel.netIp.value
        bjy_base_fragment_device_testing_result_net_name_tv.text = viewModel.netType
        bjy_base_fragment_device_testing_result_upload_speed_tv.text = "${viewModel.uploadSpeed.value} Mbps"
        bjy_base_fragment_device_testing_result_download_speed_tv.text = "${viewModel.downloadSpeed.value} Mbps"
        bjy_base_fragment_device_testing_result_upload_quality_tv.apply {
            text = getText(netQualityText[getNetQuality(viewModel.uploadSpeed.value!!)])
            setTextColor(ContextCompat.getColor(context, netQualityColor[getNetQuality(viewModel.uploadSpeed.value!!)]))
        }
        bjy_base_fragment_device_testing_result_download_quality_tv.apply {
            text = getText(netQualityText[getNetQuality(viewModel.downloadSpeed.value!!)])
            setTextColor(ContextCompat.getColor(context, netQualityColor[getNetQuality(viewModel.downloadSpeed.value!!)]))
        }
        bjy_base_fragment_device_testing_result_net_enable_iv.isEnabled = viewModel.netResult
        bjy_base_fragment_device_testing_result_camera_enable_iv.isEnabled = viewModel.cameraResult
        bjy_base_fragment_device_testing_result_speaker_enable_iv.isEnabled = viewModel.speakerResult
        bjy_base_fragment_device_testing_result_mic_enable_iv.isEnabled = viewModel.micResult
        bjy_base_fragment_device_testing_result_camera_tv.apply {
            text = if (viewModel.cameraResult) getText(R.string.bjy_base_device_testing_result_good) else getText(R.string.bjy_base_device_testing_camera_no_look)
            setTextColor(ContextCompat.getColor(context!!,
                    if (viewModel.cameraResult) R.color.bjy_base_device_testing_main_text_color
                    else R.color.bjy_base_window_loading_device_check_failed_text_color))
        }
        bjy_base_fragment_device_testing_result_speaker_tv.apply {
            text = if (viewModel.cameraResult) getText(R.string.bjy_base_device_testing_result_good) else getText(R.string.bjy_base_device_testing_speaker_no)
            setTextColor(ContextCompat.getColor(context!!,
                    if (viewModel.cameraResult) R.color.bjy_base_device_testing_main_text_color
                    else R.color.bjy_base_window_loading_device_check_failed_text_color))
        }
        bjy_base_fragment_device_testing_result_camera_tv.apply {
            text = if (viewModel.cameraResult) getText(R.string.bjy_base_device_testing_result_good) else getString(R.string.bjy_base_device_testing_mic_no)
            setTextColor(ContextCompat.getColor(context!!,
                    if (viewModel.cameraResult) R.color.bjy_base_device_testing_main_text_color
                    else R.color.bjy_base_window_loading_device_check_failed_text_color))
        }
        if (viewModel.netResult && viewModel.cameraResult && viewModel.speakerResult && viewModel.micResult) {
            bjy_base_fragment_device_testing_result_image_view.setImageResource(R.drawable.bjy_base_device_testing_result_pass)
            bjy_base_fragment_device_testing_result_text1.apply {
                text = getText(R.string.bjy_base_device_testing_result_good_tip1)
                setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_device_testing_main_text_color))
            }
            bjy_base_fragment_device_testing_result_text2.apply {
                text = getText(R.string.bjy_base_device_testing_result_good_tip2)
                setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_device_testing_main_text_color))
            }
            bjy_base_fragment_device_testing_result_positive_btn.apply {
                background = ContextCompat.getDrawable(context!!, R.drawable.bjy_base_window_loading_positive_button_bg)
                setTextColor(ContextCompat.getColor(context!!, R.color.base_white))
                setOnClickListener {
                    saveResult()
                    activity?.finish()
                }
            }
            bjy_base_fragment_device_testing_result_negative_btn.apply {
                background = ContextCompat.getDrawable(context!!, R.drawable.bjy_base_window_loading_negative_button_bg)
                setTextColor(ContextCompat.getColor(context!!, R.color.base_theme_live_product))
                setOnClickListener {
                    viewModel.isRepeatCheck = true
                    viewModel.setTestStep(DeviceTestingViewModel.TestStep.Start)
                }
            }
        } else {
            bjy_base_fragment_device_testing_result_image_view.setImageResource(R.drawable.bjy_base_device_testing_result_fail)
            bjy_base_fragment_device_testing_result_text1.apply {
                text = getText(R.string.bjy_base_device_testing_result_fail_tip1)
                setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_window_loading_device_check_failed_text_color))
            }
            bjy_base_fragment_device_testing_result_text2.apply {
                text = getText(R.string.bjy_base_device_testing_result_fail_tip2)
                setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_window_loading_device_check_failed_text_color))
            }
            bjy_base_fragment_device_testing_result_positive_btn.apply {
                background = ContextCompat.getDrawable(context!!, R.drawable.bjy_base_window_loading_negative_button_bg)
                setTextColor(ContextCompat.getColor(context!!, R.color.base_theme_live_product))
                setOnClickListener {
                    showConfirmDialog()
                }
            }
            bjy_base_fragment_device_testing_result_negative_btn.apply {
                background = ContextCompat.getDrawable(context!!, R.drawable.bjy_base_window_loading_positive_button_bg)
                setTextColor(ContextCompat.getColor(context!!, R.color.base_white))
                setOnClickListener {
                    viewModel.isRepeatCheck = true
                    viewModel.setTestStep(DeviceTestingViewModel.TestStep.Start)
                }
            }
        }
        bjy_base_fragment_device_testing_result_time_tv.text = DateFormat.getDateTimeInstance().format(Date())
    }

    private fun getNetQuality(netSpeed: Float): Int {
        return when {
            netSpeed < 0.41 -> 0
            netSpeed < 1.64 -> 1
            netSpeed < 8.39 -> 2
            netSpeed < 83.89 -> 3
            else -> 4
        }
    }

    private fun saveResult() {
        mmkv.encode("camera_status", viewModel.cameraResult)
        mmkv.encode("mic_status", viewModel.micResult)
        mmkv.encode("speaker_status", viewModel.micResult)
        mmkv.encode("os", "Android ${Build.VERSION.RELEASE}")
        mmkv.encode("client", "V ${LPReportUtil.getVersionName(context)}")
        mmkv.encode("ip", viewModel.netIp.value)
    }

    private fun showConfirmDialog() {
        val dialogFragment = DeviceTestingDialogFragment()
        dialogFragment.setTitle(getString(R.string.bjy_base_device_testing_result_confirm_question))
        dialogFragment.setContent(getString(R.string.bjy_base_device_testing_result_confirm_tip))
        dialogFragment.setNegativeButtonText(getString(R.string.bjy_base_device_testing_result_end))
        dialogFragment.setPositiveButtonText(getString(R.string.bjy_base_device_testing_result_retry))
        dialogFragment.setButtonClickedListener(object : DeviceTestingDialogFragment.OnButtonClickedListener {
            override fun onPositive() {
                viewModel.setTestStep(DeviceTestingViewModel.TestStep.Start)
                dialogFragment.dismissAllowingStateLoss()
            }

            override fun onNegative() {
                saveResult()
                dialogFragment.dismissAllowingStateLoss()
                activity?.finish()
            }
        })
        dialogFragment.show(activity!!.supportFragmentManager, "result")
    }
}